<template>
  <div class="user-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <!-- 新建用户按钮已移除，因为 API 文档未提供该接口 -->
    </div>

    <el-card>
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userPhone" label="用户手机" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="userRole" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.userRole)">
              {{ getRoleText(scope.row.userRole) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <!-- 删除用户按钮已移除，因为 API 文档未提供该接口 -->
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="userRole">
          <el-select v-model="form.userRole" placeholder="请选择角色">
            <el-option label="超管" value="0"></el-option>
            <el-option label="普通用户" value="1"></el-option>
            <el-option label="会员" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { pageQueryUserList, updateUser } from '@/api/user'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

const tableData = ref([])
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const form = reactive({
  userId: null,
  userName: '',
  userRole: '1'
})

const formRules = {
  userName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await pageQueryUserList({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    })
    tableData.value = data.list || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchList()
})

const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑用户'
  form.userId = row.id
  form.userName = row.name
  form.userRole = row.userRole
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    await updateUser(form)
    ElMessage.success('更新成功')
    
    dialogVisible.value = false
    fetchList()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchList()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    userId: null,
    userName: '',
    userRole: '1'
  })
}

const getRoleText = (role) => {
  const roles = { '0': '超管', '1': '普通用户', '2': '会员' }
  return roles[role] || '未知角色'
}

const getRoleTagType = (role) => {
  const types = { '0': 'danger', '1': 'info', '2': 'warning' }
  return types[role] || 'info'
}

</script>

<style scoped>
.user-container {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
  color: #333;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>